package com.atguigu.gulimall.product.service.impl;

import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collector;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.atguigu.common.utils.PageUtils;
import com.atguigu.common.utils.Query;

import com.atguigu.gulimall.product.dao.CategoryDao;
import com.atguigu.gulimall.product.entity.CategoryEntity;
import com.atguigu.gulimall.product.service.CategoryService;


@Service("categoryService")
public class CategoryServiceImpl extends ServiceImpl<CategoryDao, CategoryEntity> implements CategoryService {

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<CategoryEntity> page = this.page(
                new Query<CategoryEntity>().getPage(params),
                new QueryWrapper<CategoryEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public List<CategoryEntity> listWithTree() {

        // 查询出所有的分类
        List<CategoryEntity> all = this.list();

        // 组装成树形结构
        List<CategoryEntity> level1Menu = all.stream().filter(c -> {  // 获取一级子菜单
            return c.getParentCid() == 0;
        }).map( c -> {  // 获取二级子菜单
            c.setChildren(getChildrenCategory(c, all));
            return c;
        }).sorted((c1, c2) -> { // 对二级菜单排序
            return (c1.getSort() == null ? 0 : c1.getSort()) - (c2.getSort() == null ? 0 : c2.getSort());
        }).collect(Collectors.toList());
        return level1Menu;
    }

    @Override
    public void removeByIds(List<Long> catIds) {
        // TODO: 当其他数据跟此分类有关联关系的时候不能删除
        super.removeByIds(catIds);
    }

    private List<CategoryEntity> getChildrenCategory(CategoryEntity parent, List<CategoryEntity> all) {
        return all.stream().filter(c -> parent.getCatId() == c.getParentCid())
                .map(c -> {
                    c.setChildren(getChildrenCategory(c, all));
                    return c;
                }).sorted((c1, c2) -> {
                    return (c1.getSort() == null ? 0 : c1.getSort()) - (c2.getSort() == null ? 0 : c2.getSort());
                }).collect(Collectors.toList());
    }

}